package com.sh.data.engine.domain.util;

import com.google.common.collect.Lists;
import com.sh.data.engine.domain.common.model.domain.KeyValueDomain;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author boyue.wjl
 */
public class KeyValueUtil {

    public static final String COMMA_EN = ",";
    public static final String COMMA_CN = "，";
    public static final String COLON_EN = ":";
    public static final String COLON_CN = "：";

    /**
     * key/value转成json
     *
     * @param keyValueStr
     * @return
     */
    public static List<KeyValueDomain> getKeyValueList(String keyValueStr) {
        if (StringUtils.isBlank(keyValueStr)) {
            return Lists.newArrayList();
        }
        keyValueStr = keyValueStr.replaceAll(COMMA_CN, COMMA_EN).replaceAll(COLON_CN, COLON_EN);
        try {
            String[] array = keyValueStr.split(COMMA_EN);
            List<KeyValueDomain> domains = new ArrayList<>();
            for (String item : array) {
                String[] itemArray = item.split(COLON_EN);
                if (itemArray.length != 2) {
                    throw new RuntimeException();
                }
                KeyValueDomain domain = new KeyValueDomain();
                domain.setKey(itemArray[0]);
                domain.setValue(itemArray[1]);
                domains.add(domain);
            }
            return domains;
        } catch (Exception e) {
            return null;
        }
    }
}
